"""
C++ MCP server implementation with GPU support and build system awareness.

Provides C++, CUDA, and HIP code analysis tools for function call tree generation
and comprehensive code understanding through libclang integration, with enhanced
project-wide discovery capabilities and build system integration.
"""

import os
from typing import Dict, List, Any, Optional, Union
from pathlib import Path

from ...core.base_mcp import BaseMCP
from ...core.error_handler import CodeMCPError, AnalysisError, log_info, log_debug
from ...core.entry_discovery import EntryPointDiscovery, EntryDiscoveryConfig
from ...core.project_scanner import ProjectScanner, ProjectScanConfig
from ...core.function_classifier import FunctionClassifier, ClassificationConfig
from ...core.cross_file_resolver import CrossFileResolver
from .parser import CppParser
from .analyzer import CallGraphAnalyzer
from .resolver import CppResolver
from .cuda_hip import CudaHipAnalyzer
from .dynamic_calls import DynamicCallDetector
from .typing_utils import TypeAnalyzer


class CppMCP(BaseMCP):
    """C++ MCP server with CUDA/HIP GPU support and build system awareness."""
    
    def __init__(self, config=None):
        """Initialize C++ MCP server."""
        super().__init__(name="cpp_mcp", language="cpp", config=config)
        
        # Initialize analyzers
        self.parser = CppParser(config)
        self.call_analyzer = CallGraphAnalyzer()
        self.resolver = CppResolver(config)
        self.cuda_hip_analyzer = CudaHipAnalyzer()
        self.dynamic_detector = DynamicCallDetector()
        self.type_analyzer = TypeAnalyzer()
        
        # GPU support detection
        self.cuda_available = self._check_cuda_availability()
        self.hip_available = self._check_hip_availability()
        
        # Initialize discovery components with C++ specific configuration
        discovery_config = EntryDiscoveryConfig(
            languages=['cpp'],
            ignore_tests=True,
            ignore_examples=True,
            min_confidence=0.8
        )
        self.entry_discovery = EntryPointDiscovery(discovery_config)
        
        scan_config = ProjectScanConfig(
            language_filters=['cpp'],
            include_build_files=True,
            build_systems=['cmake', 'make', 'bazel', 'vcpkg', 'meson'],
            max_depth=10
        )
        self.project_scanner = ProjectScanner(scan_config)
        
        classification_config = ClassificationConfig(
            language='cpp',
            min_confidence=0.7
        )
        self.function_classifier = FunctionClassifier(classification_config)
        
        self.cross_file_resolver = CrossFileResolver()
        
        # Register C++ and GPU analysis tools
        self._register_tools()
        
        log_info(f"Initialized Enhanced C++ MCP with CUDA: {self.cuda_available}, HIP: {self.hip_available}, Build system detection enabled")
    
    def register_tool(self, name: str, description: str, parameters: dict, handler: callable):
        """Register a tool with the MCP server."""
        if not hasattr(self, 'tools'):
            self.tools = []
        
        self.tools.append({
            'name': name,
            'description': description,
            'parameters': parameters,
            'handler': handler
        })
    
    def _register_tools(self):
        """Register C++, GPU analysis, and build system discovery tools."""
        
        # Standard C++ analysis tool
        self.register_tool(
            name="analyze_file",
            description="Analyze a C++ file for function calls, classes, and structure including GPU kernels",
            parameters={
                "type": "object",
                "properties": {
                    "file_path": {"type": "string", "description": "Path to C++ file (.cpp, .cxx, .cu, etc.)"},
                    "include_gpu_analysis": {"type": "boolean", "default": True, "description": "Include CUDA/HIP GPU analysis"},
                    "include_templates": {"type": "boolean", "default": True, "description": "Analyze template instantiations"},
                    "include_inheritance": {"type": "boolean", "default": True, "description": "Analyze class hierarchies"},
                    "detect_dynamic_calls": {"type": "boolean", "default": True, "description": "Detect dynamic function calls"}
                },
                "required": ["file_path"]
            },
            handler=self._analyze_file
        )
        
        # Build system and project discovery tools
        self.register_tool(
            name="discover_cpp_project",
            description="Discover C++ project structure, build system, and entry points",
            parameters={
                "type": "object",
                "properties": {
                    "project_path": {
                        "type": "string",
                        "description": "Path to the C++ project root directory"
                    },
                    "detect_build_system": {
                        "type": "boolean",
                        "description": "Whether to detect and analyze build system",
                        "default": True
                    },
                    "include_entry_points": {
                        "type": "boolean",
                        "description": "Whether to discover entry points",
                        "default": True
                    },
                    "analyze_dependencies": {
                        "type": "boolean",
                        "description": "Whether to analyze external dependencies",
                        "default": True
                    }
                },
                "required": ["project_path"]
            },
            handler=self._discover_cpp_project
        )
        
        self.register_tool(
            name="analyze_build_system",
            description="Analyze C++ project build system (CMake, Make, Bazel, etc.)",
            parameters={
                "type": "object",
                "properties": {
                    "project_path": {
                        "type": "string",
                        "description": "Path to the project root directory"
                    },
                    "build_system": {
                        "type": "string",
                        "description": "Specific build system to analyze (auto-detect if not provided)"
                    },
                    "extract_targets": {
                        "type": "boolean",
                        "description": "Extract build targets and dependencies",
                        "default": True
                    }
                },
                "required": ["project_path"]
            },
            handler=self._analyze_build_system
        )
        
        self.register_tool(
            name="resolve_cpp_headers",
            description="Resolve header file dependencies across the project",
            parameters={
                "type": "object",
                "properties": {
                    "project_path": {
                        "type": "string",
                        "description": "Path to the project root directory"
                    },
                    "target_files": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "Specific files to analyze (optional)"
                    },
                    "include_system_headers": {
                        "type": "boolean",
                        "description": "Include system/standard library headers",
                        "default": False
                    }
                },
                "required": ["project_path"]
            },
            handler=self._resolve_cpp_headers
        )
        
        self.register_tool(
            name="find_cpp_entry_points",
            description="Find all entry points in a C++ project including main functions and exported symbols",
            parameters={
                "type": "object",
                "properties": {
                    "project_path": {
                        "type": "string",
                        "description": "Path to the project root directory"
                    },
                    "include_gpu_kernels": {
                        "type": "boolean",
                        "description": "Include GPU kernels as entry points",
                        "default": True
                    },
                    "entry_types": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "Types of entry points to find",
                        "default": ["main", "kernel", "export"]
                    }
                },
                "required": ["project_path"]
            },
            handler=self._find_cpp_entry_points
        )
        
        self.register_tool(
            name="analyze_cpp_project_tree",
            description="Generate comprehensive call tree for entire C++ project",
            parameters={
                "type": "object",
                "properties": {
                    "project_path": {
                        "type": "string",
                        "description": "Path to the project root directory"
                    },
                    "entry_point": {
                        "type": "string",
                        "description": "Starting entry point (auto-discovered if not provided)"
                    },
                    "max_depth": {
                        "type": "integer",
                        "description": "Maximum tree depth",
                        "default": 20
                    },
                    "include_templates": {
                        "type": "boolean",
                        "description": "Include template instantiations",
                        "default": True
                    },
                    "include_gpu_calls": {
                        "type": "boolean",
                        "description": "Include GPU kernel launches",
                        "default": True
                    }
                },
                "required": ["project_path"]
            },
            handler=self._analyze_cpp_project_tree
        )
    
    async def _discover_cpp_project(self, project_path: str, detect_build_system: bool = True,
                                   include_entry_points: bool = True, analyze_dependencies: bool = True) -> Dict[str, Any]:
        """Discover C++ project structure and build system."""
        try:
            project_path = Path(project_path)
            if not project_path.exists():
                raise AnalysisError(f"Project path not found: {project_path}")
            
            log_info(f"Discovering C++ project: {project_path}")
            
            # Scan project structure
            project_info = self.project_scanner.scan_project(project_path)
            
            result = {
                'status': 'success',
                'project_path': str(project_path),
                'project_info': project_info
            }
            
            # Detect build system if requested
            if detect_build_system:
                build_system_info = await self._analyze_build_system(str(project_path))
                result['build_system'] = build_system_info
            
            # Discover entry points if requested
            if include_entry_points:
                entry_points = self.entry_discovery.discover_entry_points(project_path)
                result['entry_points'] = [ep.__dict__ for ep in entry_points]
            
            # Analyze dependencies if requested
            if analyze_dependencies:
                cpp_files = [f for f in project_info.get('files', []) 
                           if f.get('language') == 'cpp']
                
                dependency_info = await self._resolve_cpp_headers(
                    str(project_path), 
                    target_files=[f['path'] for f in cpp_files[:10]]  # Limit for performance
                )
                result['dependencies'] = dependency_info
            
            return result
            
        except Exception as e:
            log_info(f"Error discovering C++ project {project_path}: {e}")
            raise AnalysisError(f"Failed to discover C++ project: {e}")
    
    async def _analyze_build_system(self, project_path: str, build_system: str = None, 
                                   extract_targets: bool = True) -> Dict[str, Any]:
        """Analyze C++ project build system."""
        try:
            project_path = Path(project_path)
            
            # Detect build system if not specified
            detected_systems = []
            
            # Check for CMake
            if (project_path / 'CMakeLists.txt').exists():
                detected_systems.append('cmake')
            
            # Check for Make
            if (project_path / 'Makefile').exists() or (project_path / 'makefile').exists():
                detected_systems.append('make')
            
            # Check for Bazel
            if (project_path / 'BUILD').exists() or (project_path / 'BUILD.bazel').exists():
                detected_systems.append('bazel')
            
            # Check for Meson
            if (project_path / 'meson.build').exists():
                detected_systems.append('meson')
            
            # Check for vcpkg
            if (project_path / 'vcpkg.json').exists():
                detected_systems.append('vcpkg')
            
            result = {
                'project_path': str(project_path),
                'detected_build_systems': detected_systems,
                'primary_build_system': build_system or (detected_systems[0] if detected_systems else 'unknown')
            }
            
            # Extract build targets if requested
            if extract_targets and detected_systems:
                targets_info = await self._extract_build_targets(project_path, detected_systems[0])
                result['build_targets'] = targets_info
            
            return result
            
        except Exception as e:
            log_info(f"Error analyzing build system in {project_path}: {e}")
            raise AnalysisError(f"Failed to analyze build system: {e}")
    
    async def _extract_build_targets(self, project_path: Path, build_system: str) -> Dict[str, Any]:
        """Extract build targets from build system files."""
        targets_info = {
            'build_system': build_system,
            'targets': [],
            'libraries': [],
            'executables': []
        }
        
        try:
            if build_system == 'cmake':
                cmake_file = project_path / 'CMakeLists.txt'
                if cmake_file.exists():
                    with open(cmake_file, 'r') as f:
                        content = f.read()
                    
                    # Simple regex-based extraction (in practice, would use a CMake parser)
                    import re
                    
                    # Find executables
                    exe_matches = re.findall(r'add_executable\s*\(\s*(\w+)', content, re.IGNORECASE)
                    targets_info['executables'] = exe_matches
                    
                    # Find libraries
                    lib_matches = re.findall(r'add_library\s*\(\s*(\w+)', content, re.IGNORECASE)
                    targets_info['libraries'] = lib_matches
                    
                    targets_info['targets'] = exe_matches + lib_matches
            
            elif build_system == 'make':
                makefile = project_path / 'Makefile'
                if not makefile.exists():
                    makefile = project_path / 'makefile'
                
                if makefile.exists():
                    with open(makefile, 'r') as f:
                        content = f.read()
                    
                    # Extract targets (simplified)
                    import re
                    target_matches = re.findall(r'^(\w+)\s*:', content, re.MULTILINE)
                    targets_info['targets'] = [t for t in target_matches if t not in ['clean', 'install', 'all']]
            
        except Exception as e:
            log_debug(f"Error extracting build targets: {e}")
        
        return targets_info
    
    async def _resolve_cpp_headers(self, project_path: str, target_files: List[str] = None,
                                  include_system_headers: bool = False) -> Dict[str, Any]:
        """Resolve header file dependencies across the project."""
        try:
            project_path = Path(project_path)
            
            # Get files to analyze
            if target_files:
                files_to_analyze = [project_path / f for f in target_files]
            else:
                project_info = self.project_scanner.scan_project(project_path)
                files_to_analyze = [Path(f['path']) for f in project_info.get('files', []) 
                                  if f.get('language') == 'cpp']
            
            # Resolve dependencies using cross-file resolver
            resolution_result = self.cross_file_resolver.resolve_dependencies(
                files_to_analyze, project_path
            )
            
            # Filter system headers if not requested
            if not include_system_headers:
                filtered_deps = []
                for dep in resolution_result.get('dependencies', []):
                    if not dep.get('is_system', False):
                        filtered_deps.append(dep)
                resolution_result['dependencies'] = filtered_deps
            
            return {
                'status': 'success',
                'project_path': str(project_path),
                'resolution_result': resolution_result,
                'statistics': {
                    'files_analyzed': len(files_to_analyze),
                    'header_dependencies': len(resolution_result.get('dependencies', [])),
                    'include_chains': len(resolution_result.get('include_chains', [])),
                    'circular_dependencies': len(resolution_result.get('circular_deps', []))
                }
            }
            
        except Exception as e:
            log_info(f"Error resolving C++ headers in {project_path}: {e}")
            raise AnalysisError(f"Failed to resolve C++ headers: {e}")
    
    async def _find_cpp_entry_points(self, project_path: str, include_gpu_kernels: bool = True,
                                    entry_types: List[str] = None) -> Dict[str, Any]:
        """Find all entry points in a C++ project."""
        try:
            project_path = Path(project_path)
            
            if entry_types is None:
                entry_types = ["main", "kernel", "export"]
            
            log_info(f"Finding C++ entry points in: {project_path}")
            
            # Discover all entry points
            all_entry_points = self.entry_discovery.discover_entry_points(project_path)
            
            # Filter by requested types
            filtered_entry_points = [
                ep for ep in all_entry_points 
                if ep.entry_type in entry_types
            ]
            
            # Add GPU kernels if requested
            if include_gpu_kernels and (self.cuda_available or self.hip_available):
                gpu_kernels = await self._find_gpu_kernels(project_path)
                # Convert GPU kernels to entry point format
                for kernel in gpu_kernels:
                    from ...core.entry_discovery import EntryPoint
                    kernel_entry = EntryPoint(
                        name=kernel['name'],
                        file_path=kernel['file_path'],
                        line_number=kernel['line_number'],
                        language='cpp',
                        entry_type='kernel',
                        confidence=0.9,
                        signature=kernel['signature'],
                        context={'gpu_kernel': True, 'api': kernel.get('api', 'CUDA')}
                    )
                    filtered_entry_points.append(kernel_entry)
            
            # Group and analyze
            by_type = {}
            by_file = {}
            
            for ep in filtered_entry_points:
                if ep.entry_type not in by_type:
                    by_type[ep.entry_type] = []
                by_type[ep.entry_type].append(ep.__dict__)
                
                if ep.file_path not in by_file:
                    by_file[ep.file_path] = []
                by_file[ep.file_path].append(ep.__dict__)
            
            return {
                'status': 'success',
                'project_path': str(project_path),
                'entry_points': [ep.__dict__ for ep in filtered_entry_points],
                'by_type': by_type,
                'by_file': by_file,
                'statistics': {
                    'total_found': len(filtered_entry_points),
                    'types_found': list(by_type.keys()),
                    'files_with_entries': len(by_file),
                    'gpu_kernels_found': len(by_type.get('kernel', []))
                }
            }
            
        except Exception as e:
            log_info(f"Error finding C++ entry points in {project_path}: {e}")
            raise AnalysisError(f"Failed to find C++ entry points: {e}")
    
    async def _find_gpu_kernels(self, project_path: Path) -> List[Dict[str, Any]]:
        """Find GPU kernels in the project."""
        kernels = []
        
        try:
            # Find GPU source files
            gpu_extensions = ['.cu', '.cuh', '.hip']
            gpu_files = []
            
            for file_path in project_path.rglob('*'):
                if file_path.suffix in gpu_extensions:
                    gpu_files.append(file_path)
            
            # Also check regular C++ files for GPU code
            for file_path in project_path.rglob('*.cpp'):
                try:
                    with open(file_path, 'r') as f:
                        content = f.read()
                    if '__global__' in content or '__device__' in content:
                        gpu_files.append(file_path)
                except:
                    continue
            
            # Analyze each GPU file
            for gpu_file in gpu_files:
                try:
                    ast_data = await self.parse_file(str(gpu_file))
                    if 'gpu_analysis' in ast_data:
                        gpu_analysis = ast_data['gpu_analysis']
                        for kernel in gpu_analysis.get('device_functions', []):
                            if kernel.get('is_kernel', False):
                                kernels.append({
                                    'name': kernel['name'],
                                    'file_path': str(gpu_file),
                                    'line_number': kernel.get('line_number', 0),
                                    'signature': kernel.get('signature', ''),
                                    'api': gpu_analysis.get('programming_model', 'CUDA')
                                })
                except Exception as e:
                    log_debug(f"Error analyzing GPU file {gpu_file}: {e}")
                    continue
            
        except Exception as e:
            log_debug(f"Error finding GPU kernels: {e}")
        
        return kernels
    
    async def _analyze_cpp_project_tree(self, project_path: str, entry_point: str = None,
                                       max_depth: int = 20, include_templates: bool = True,
                                       include_gpu_calls: bool = True) -> Dict[str, Any]:
        """Generate comprehensive call tree for entire C++ project."""
        try:
            project_path = Path(project_path)
            
            log_info(f"Analyzing C++ project call tree: {project_path}")
            
            # Discover entry point if not provided
            if not entry_point:
                entry_points = self.entry_discovery.discover_entry_points(project_path)
                best_entry = self.entry_discovery.get_best_entry_point(entry_points)
                if not best_entry:
                    raise AnalysisError("No suitable entry point found in C++ project")
                entry_point = f"{best_entry.file_path}:{best_entry.name}"
                log_info(f"Auto-discovered entry point: {entry_point}")
            
            # Parse entry point
            if ':' in entry_point:
                file_path, function_name = entry_point.split(':', 1)
            else:
                file_path = entry_point
                function_name = "main"
            
            # Resolve cross-file dependencies
            dependency_result = await self._resolve_cpp_headers(str(project_path))
            
            # Build comprehensive call tree
            call_tree_result = await self._get_call_tree(
                file_path, function_name, max_depth, include_gpu_calls
            )
            
            # Enhance with cross-file information
            enhanced_tree = self._enhance_tree_with_cross_file_info(
                call_tree_result['call_tree'],
                dependency_result['resolution_result']
            )
            
            return {
                'status': 'success',
                'project_path': str(project_path),
                'entry_point': entry_point,
                'call_tree': enhanced_tree,
                'cross_file_dependencies': dependency_result['resolution_result'],
                'statistics': {
                    'total_nodes': enhanced_tree.get('statistics', {}).get('node_count', 1),
                    'max_depth': enhanced_tree.get('statistics', {}).get('max_depth', 1),
                    'cross_file_calls': enhanced_tree.get('statistics', {}).get('cross_file_calls', 0),
                    'template_instantiations': enhanced_tree.get('statistics', {}).get('template_calls', 0),
                    'gpu_kernel_calls': enhanced_tree.get('statistics', {}).get('gpu_calls', 0),
                    'files_involved': len(set(node.get('file_path', '') for node in 
                                           self._flatten_tree_nodes(enhanced_tree)))
                }
            }
            
        except Exception as e:
            log_info(f"Error analyzing C++ project tree for {project_path}: {e}")
            raise AnalysisError(f"Failed to analyze C++ project tree: {e}")
    
    def _enhance_tree_with_cross_file_info(self, call_tree: Dict[str, Any], 
                                          dependency_info: Dict[str, Any]) -> Dict[str, Any]:
        """Enhance call tree with cross-file dependency information."""
        enhanced_tree = call_tree.copy()
        enhanced_tree['cross_file_info'] = dependency_info
        
        # Add statistics about cross-file relationships
        if 'statistics' not in enhanced_tree:
            enhanced_tree['statistics'] = {}
        
        enhanced_tree['statistics']['cross_file_calls'] = len(dependency_info.get('call_graph', {}))
        enhanced_tree['statistics']['include_chains'] = len(dependency_info.get('include_chains', []))
        
        return enhanced_tree
    
    def _flatten_tree_nodes(self, tree: Dict[str, Any]) -> List[Dict[str, Any]]:
        """Flatten tree nodes for analysis."""
        nodes = []
        if 'root' in tree:
            nodes.append(tree['root'])
        if 'children' in tree:
            for child in tree['children']:
                nodes.extend(self._flatten_tree_nodes(child))
        return nodes
    
    async def _register_default_tools(self):
        """Register default tools for this MCP server."""
        pass  # Handled by _register_tools()
    
    async def _initialize_language_components(self):
        """Initialize language-specific components."""
        pass  # Components initialized in __init__
    
    def _is_supported_file(self, file_path: Path) -> bool:
        """Check if file is supported by this MCP server."""
        return self.parser.is_supported_file(str(file_path))
    
    def _get_supported_extensions(self) -> List[str]:
        """Get list of supported file extensions."""
        return self.parser.get_supported_extensions()
    
    async def parse_file(self, file_path: str) -> Any:
        """Parse a C++ file and return AST structure."""
        file_path = Path(file_path)
        if not file_path.exists():
            raise AnalysisError(f"File not found: {file_path}")
        
        log_info(f"Parsing C++ file: {file_path}")
        
        # Read source code for GPU pattern analysis
        with open(file_path, 'r', encoding='utf-8') as f:
            source_code = f.read()
        
        # Parse with C++ parser
        ast_data = self.parser.parse_file(str(file_path))
        
        # Add GPU-specific analysis if GPU code detected
        programming_model = self.cuda_hip_analyzer._detect_programming_model(ast_data, source_code)
        if programming_model != 'Standard C++':
            gpu_analysis = self.cuda_hip_analyzer.analyze_gpu_code(ast_data, source_code)
            ast_data['gpu_analysis'] = gpu_analysis
            ast_data['programming_model'] = programming_model
        
        return ast_data
    
    async def _get_call_tree(self, file_path: str, entry_function: str, 
                            max_depth: int = 10, include_gpu_kernels: bool = True) -> Dict[str, Any]:
        """Generate call tree with GPU kernel support."""
        try:
            ast_data = await self.parse_file(file_path)
            
            # Find entry function
            func_info = await self._extract_function_info(ast_data, entry_function)
            if not func_info:
                return {'error': f'Entry function {entry_function} not found in {file_path}'}
            
            # Generate call graph
            if include_gpu_kernels and 'gpu_analysis' in ast_data:
                with open(file_path, 'r', encoding='utf-8') as f:
                    source_code = f.read()
                call_graph = self.call_analyzer.analyze_gpu_call_graph(
                    func_info, ast_data, source_code, max_depth
                )
            else:
                call_graph = self.call_analyzer.analyze_function_calls(func_info, ast_data, max_depth)
            
            # Build hierarchical tree
            call_tree = self.call_analyzer.build_call_tree(call_graph, include_external=True)
            
            return {
                'entry_function': entry_function,
                'file_path': file_path,
                'call_tree': call_tree,
                'supports_gpu': include_gpu_kernels and 'gpu_analysis' in ast_data
            }
            
        except Exception as e:
            log_debug(f"Error generating call tree for {entry_function}: {e}")
            raise AnalysisError(f"Failed to generate call tree: {e}")
    
    async def _extract_function_info(self, ast_data: Any, function_name: str) -> Optional[Dict[str, Any]]:
        """Extract function information from AST data."""
        if not isinstance(ast_data, dict) or 'functions' not in ast_data:
            return None
        
        for func in ast_data['functions']:
            if func['name'] == function_name:
                # Enhance with GPU information if available
                func_info = func.copy()
                
                # Check if this is a GPU function
                if 'gpu_analysis' in ast_data:
                    device_funcs = ast_data['gpu_analysis']['device_functions']
                    for device_func in device_funcs:
                        if device_func['qualified_name'] == func['qualified_name']:
                            func_info['gpu_attributes'] = device_func['gpu_attributes']
                            func_info['is_gpu_kernel'] = device_func['is_kernel']
                            func_info['is_device_function'] = device_func['is_device_function']
                            break
                
                return func_info
        
        return None
    
    def _check_cuda_availability(self) -> bool:
        """Check if CUDA toolkit is available."""
        try:
            # Check for CUDA installation
            cuda_home = os.environ.get('CUDA_HOME') or os.environ.get('CUDA_PATH')
            if cuda_home and Path(cuda_home).exists():
                return True
            
            # Check common installation paths
            cuda_paths = ['/usr/local/cuda', '/opt/cuda']
            for path in cuda_paths:
                if Path(path).exists():
                    return True
            
            return False
        except Exception:
            return False
    
    def _check_hip_availability(self) -> bool:
        """Check if HIP/ROCm is available."""
        try:
            # Check for ROCm installation
            rocm_home = os.environ.get('ROCM_PATH') or os.environ.get('HIP_PATH')
            if rocm_home and Path(rocm_home).exists():
                return True
            
            # Check common installation paths
            hip_paths = ['/opt/rocm', '/usr/hip']
            for path in hip_paths:
                if Path(path).exists():
                    return True
            
            return False
        except Exception:
            return False
    
    def get_supported_extensions(self) -> List[str]:
        """Return list of supported file extensions."""
        return ['.cpp', '.cxx', '.cc', '.c', '.h', '.hpp', '.hxx', '.cu', '.cuh', '.hip']
    
    def get_language_info(self) -> Dict[str, Any]:
        """Return information about C++ language support."""
        return {
            'language': 'cpp',
            'standards_support': ['C++11', 'C++14', 'C++17', 'C++20'],
            'gpu_support': {
                'cuda_available': self.cuda_available,
                'hip_available': self.hip_available
            },
            'build_systems': ['cmake', 'make', 'bazel', 'meson', 'vcpkg'],
            'features': [
                'Template analysis',
                'Inheritance hierarchies', 
                'Virtual function dispatch',
                'Move semantics analysis',
                'CUDA kernel analysis',
                'HIP kernel analysis',
                'Build system integration',
                'Header dependency resolution',
                'Cross-file call analysis'
            ],
            'limitations': [
                'Complex template metaprogramming may not be fully analyzed',
                'Dynamic loading (dlopen) cannot be statically analyzed',
                'Some preprocessor constructs may be simplified'
            ]
        }